package com.hongmeng.teamwork.domain.impl;

import com.alibaba.fastjson.JSON;
import com.hongmeng.teamwork.domain.IMessageDomainService;
import com.hongmeng.teamwork.entity.dto.MessageDto;
import com.hongmeng.teamwork.utils.FeishuUtil;
import com.lark.oapi.Client;
import com.lark.oapi.service.im.v1.model.CreateMessageReq;
import com.lark.oapi.service.im.v1.model.CreateMessageReqBody;
import com.lark.oapi.service.im.v1.model.CreateMessageResp;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;

@Log4j2
@Service
public class MessageDomainServiceImpl implements IMessageDomainService {

    @Resource
    private Client client;

    @Override
    public void sendMessage(MessageDto messageDto) {
        try {
            CreateMessageResp resp = client.im().message()
                    .create(CreateMessageReq.newBuilder()
                                    .receiveIdType(messageDto.getReceiveIdType())
                                    .createMessageReqBody(CreateMessageReqBody.newBuilder()
                                            .receiveId(messageDto.getReceiveId())
                                            .msgType("interactive")
                                            .content(messageDto.getContent())
                                            .uuid(UUID.randomUUID().toString())
                                            .build())
                                    .build(),
                            FeishuUtil.getRequestOptionsByAccessToken(messageDto.getAccessToken()));
            if (resp.success()) {
                if (log.isInfoEnabled()) {
                    log.info("消息发送成功, resp: {}", JSON.toJSONString(resp));
                }
            } else {
                log.error("消息发送失败, resp: {}", JSON.toJSONString(resp));
            }
        } catch (Exception e) {
            log.error("MessageDomainServiceImpl.sendMessage.error: {}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
}
